// pages/shopping/goodsDetail/goodsDetail.js
var sliderWidth = 355; // 需要设置slider的宽度，用于计算中间位置
var app = getApp();
var _PAGE = 1;
var _PAGESIZE = 10;
var WxParse = require('../../../wxParse/wxParse.js');
var util = require("../../../utils/util.js");
var mta = require('../../../utils/mta_analysis.js');
var choose_package_id= ''; //所选套餐id
var userInfo= [];
var is_rent_eq= false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    starss: 5,
    equipments_id: '', //缴费器id
    iconShare: '../../../images/goods_share.png',
    praiseGrey: '../../../images/praise_grey.png',
    praiseRed: '../../../images/praise_red.png',
    starPic: '../../../images/star.png',
    chooseClose: '../../../images/cha1.png',
    activeIcon: '../../../images/active_icon.png',
    close_invoice: '../../../images/close_invoice.png',
    fenx: '../../../images/wx-icon.png',
    fenxian: '../../../images/code-icon.png',
    imgUrls: [
      '../../../images/goods_banner.jpg',
      '../../../images/goods_banner.jpg',
      '../../../images/goods_banner.jpg'
    ], //banner图
    indicatorDots: true, //是否显示面板指示点
    autoplay: true, //是否自动切换
    interval: 3000, //自动切换时间间隔
    current: 0, //当前所在滑块的 index
    equipments: {}, //缴费器信息
    moneyNUm: 0,
    tabs: ["商品详情"],
    activeIndex: 0,
    choosetabs: [{
        name: "租赁时长",
        mode: 1
      },
      // {
      //   name: "流量付费",
      //   mode: 2
      // }
    ],
    chooseIndex: 0,
    chooseTimeIndex: 0,
    // chooseTrafficIndex: 0,
    chooseMode: 1, //默认套餐模式
    chooseName: '',
    isShowMask: true,
    reviews: [],
    checked: false,
    isShowNote: true,
    isShare: true,
    aniStyle: false,
    packages: [], //套餐列表
    empty: true,
    hasMore: false, //数据是否加载完成
    loading: false,
    loadShow: false, //空数据图片展示
    load_show: true, //切换详情与晒单
    isPackages: false, //套餐数据加载完
    width: 0,
    cecan_money:0,//次年年费
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          width: res.windowWidth
        })
      },
    })
    mta.Page.init();
    wx.showLoading({
      title: '加载中...',
    })
    var equipments_id = '';
    var pid = '';
    var way = '';
    var pro = '';//推广商ID
    var cha = '';//渠道ID
    //二维码进入获取参数
    if (util.isExitsVariable(options.scene)) {
      var scene = util.sceneToArr(decodeURIComponent(options.scene));
      if (util.isExitsVariable(scene.pid)) {
        pid = scene.pid;
        way = scene.way;
      }
      if (util.isExitsVariable(scene.eq_id)) {
        equipments_id = scene.eq_id;
      }
      //推广商ID
      if (util.isExitsVariable(scene.pro)) {
        pro = scene.pro;
      }
      //渠道ID
      if (util.isExitsVariable(scene.cha)) {
        cha = scene.cha;
      }

    }
    //页面分享进入
    if (util.isExitsVariable(options.equipments_id)) {
      equipments_id = options.equipments_id;
    }
    if (util.isExitsVariable(options.pid)) {
      pid = options.pid;
      way = options.way;
    }
    //渠道ID
    if (util.isExitsVariable(options.pro)) {
      pro = options.pro;
    }
    //渠道ID
    if (util.isExitsVariable(options.cha)) {
      cha = options.cha;
    }

    that.setData({
      equipments_id: equipments_id
    })
    //保存到缓存
    if (pid != '') {
      wx.setStorageSync("pid", pid);
      wx.setStorageSync("way", way);
    }
    if (pro != '') {
      wx.setStorageSync("promoter", pro);//推广商ID
    }
    if (cha != '') {
      wx.setStorageSync("channel", cha);//渠道ID
    }
    that.getGoodsDetail();

    that.getEvaluateList();
    that.shareLogHistory();//浏览记录
    //that.getGoodsRentalPackage();
    // const getGoodsDetail = that.getGoodsDetail();
    // const getGoodsRentalPackage = that.getGoodsRentalPackage();

    // Promise.all([
    //   getGoodsDetail,
    //   getGoodsRentalPackage
    // ]).then(([getGoodsDetail, getGoodsRentalPackage]) => console.log(0));
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    // 清空用户之前选中的优惠券信息
    wx.setStorageSync('coupon_id', ''); // 优惠券ID
    wx.setStorageSync('coupon_money', 0); // 优惠券金额
    wx.setStorageSync('coupon_name', '使用'); // 优惠券名称
    if (util.isExitsVariable(wx.getStorageSync('user_id'))){
      that.getUserInfo();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    var activeIndex = that.data.activeIndex;
    if (activeIndex == 1) {
      var hasMore = that.data.hasMore;
      if (!hasMore) {
        return false;
      }
      _PAGE++;
      that.setData({
        loading: true
      })
      that.getEvaluateList();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var that = this;
    that.shareLogFun(1);
    if (res.from === 'button') {
      // 来自页面内转发按钮
      //console.log(res.target)
    }
    this.setData({
      isShare: true
    })
    var equipments_name = that.data.equipments.equipments_name;
    var main_pic = that.data.equipments.main_pic;
    var equipments_id = that.data.equipments.equipments_id;
    var user_id = wx.getStorageSync('user_id');
    var pro = wx.getStorageSync('promoter');
    var cha = wx.getStorageSync('channel');
    if (!is_rent_eq){
      user_id = '';
    }
    return {
      title: '发现好产品' + equipments_name + '啦，赶快来购买~',
      path: 'pages/shopping/goodsDetail/goodsDetail?equipments_id=' + equipments_id + "&pid=" + user_id + "&way=3"+"&pro="+pro+"&cha="+cha,
      imageUrl: main_pic
    }
  },

  //选项卡切换
  tabClick: function(e) {
    if (e.currentTarget.id == 1) {
      var load_show = false
    } else {
      var load_show = true
    }
    this.setData({
      activeIndex: e.currentTarget.id,
      load_show: load_show
    });
    // if (e.currentTarget.id==1){
    //   // wx.showLoading({
    //   //   title: '加载中...',
    //   // })

    // }
  },
  //点赞
  giveLike: function(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let praiseType = 'reviews[' + index + '].praiseType';
    that.setData({
      [praiseType]: 1
    })
  },
  //商品型号选择
  chooseSize: function() {
    var that = this;
    that.goBuy()
  },

  //商品出租方式切换
  chooseTabClick: function(e) {
    var that = this;
    that.setData({
      chooseIndex: e.currentTarget.id,
      chooseMode: e.currentTarget.dataset.mode,
      packages: [],
      isPackages: false
    })
    that.getGoodsRentalPackage();
  },

  //选择套餐
  chooseTime: function(e) {
    let that = this;
    let i = e.currentTarget.dataset.index;
    let package_id = e.currentTarget.dataset.package_id;
    let total_price = that.data.packages[i].total_money;
    let cecan_money = '';
    if (util.isExitsVariable(that.data.packages[i])) {
      cecan_money = that.data.packages[i].renew_money;
    }
    console.log('次年费用', that.data.packages, cecan_money);
    var mode = that.data.chooseMode;
    if (mode == 1) {
      var text = '天租赁时间';
    } else if (mode == 2) {
      var text = 'L租赁流量';
    }
    let chooseText = that.data.packages[i].num + text;
    choose_package_id = package_id
    that.setData({
      chooseTimeIndex: i,
      chooseName: chooseText,
      moneyNUm: total_price,
      cecan_money: cecan_money
    })
  },
  // //选择流量
  // chooseTraffic: function (e) {
  //   let that = this;
  //   let i = e.currentTarget.dataset.index;
  //   let total_price = that.data.packages[i].total_money;
  //   let chooseText = that.data.packages[i].num + 'L租赁流量';
  //   that.setData({
  //     chooseTrafficIndex: i,
  //     chooseName: chooseText,
  //     moneyNUm: total_price
  //   })
  // },
  //遮罩时阻止滚动
  myCatchTouch: function() {
    return;
  },
  //点击遮罩关闭弹窗
  // hiddenMask:function(){
  //   console.log(this);
  //   let that = this;
  //   that.setData({
  //     isShowMask: true
  //   })
  // },
  //关闭类型选择
  closeChoose: function() {
    let that = this;
    that.setData({
      isShowMask: true
    })
  },
  //点击分享
  goodsShare: function() {
    this.setData({
      isShare: false,
      aniStyle: true
    })
  },
  //关闭分享
  closeShare: function() {
    var that = this;
    that.setData({
      aniStyle: false
    })
    setTimeout(function() {
      that.setData({
        isShare: true
      })
    }, 401)
  },
  //分享选择
  chooseShare() {
    var that = this;
    that.setData({
      aniStyle: false,
      isShare: true
    })
    if (!is_rent_eq) {
      wx.showModal({
        content: '签约后才可进行分享',
        showCancel: false,
        success(res) {
          if (res.confirm) {

          }
        }
      })
    } else {
      that.shareLogFun(2);//分享
      wx.navigateTo({
        url: '../goodsShare/goodsShare?equipments_id=' + this.data.equipments_id,
      })
    }

  },


  // 立即购买
  goBuy: function() {
    var that = this;
    that.setData({
      isShowMask: true
    })
    var equipments_id = that.data.equipments_id;
    var token = wx.getStorageSync("token");
    app.loginStatus(function() {
      wx.navigateTo({
        url: '../orderConfirm/orderConfirm?equipments_id=' + equipments_id
      })
    }, function() {
      app.showModal("", "您还未登录，请先登录", function() {
        wx.navigateTo({
          url: '/pages/user/login/login',
        })
      }, function() {
        wx.setStorageSync('is_login', false);
      });
    });
  },

  //查询商品详情
  getGoodsDetail() {
    var that = this;
    var equipments_id = that.data.equipments_id;
    app.ajax({
      url: 'User/Equipment/equipmentsDetail',
      method: "POST",
      data: {
        equipments_id: equipments_id
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.code == 1000) {
          var article = res.data.data.detail;
          WxParse.wxParse('article', 'html', article, that, 5);
          that.setData({
            equipments: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },

  //获取缴费器套餐  此接口已经删除
  getGoodsRentalPackage: function() {
    var that = this;
    var equipments_id = that.data.equipments_id;
    var mode = that.data.chooseMode;
    that.setData({
      isPackages: false
    })
    app.ajax({
      url: 'User/Equipment/equipmentRentalPackage',
      method: "POST",
      data: {
        equipments_id: equipments_id,
        mode: mode
      },
      success: function(res) {
        if (res.data.code == 1000) {
          if (mode == 1) {
            var text = '天租赁时间';
          } else if (mode == 2) {
            var text = 'L租赁流量';
          }
          let i = 0;
          var total_price = 0.00;
          var chooseText = '';
          var choose_spackage_ids = '';
          var packages = [];
          if (res.data.data.length > 0) {
            packages = res.data.data;
            total_price = res.data.data[i].total_money;
            chooseText = res.data.data[i].num + text;
            choose_spackage_ids = res.data.data[i].package_id;
          }
          var cecan_money = '';
          if (util.isExitsVariable(res.data.data[i])){
            cecan_money = res.data.data[i].renew_money;
          }
          that.setData({
            packages: packages,
            chooseTimeIndex: i,
            chooseName: chooseText,
            moneyNUm: total_price,
            cecan_money: cecan_money,
            isPackages: true
          })
          choose_package_id = choose_spackage_ids
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //选择
  checkChange: function() {
    let that = this;
    let checked = !that.data.checked;
    that.setData({
      checked: checked
    })
  },
  //关闭下单须知
  closeNote: function() {
    let that = this;
    that.setData({
      isShowNote: true
    })
  },
  //不同意下单须知
  cancel: function() {
    let that = this;
    that.setData({
      isShowNote: true
    })
  },
  //同意下单须知
  confirm: function() {
    let that = this;
    var checked = that.data.checked;
    if (checked) {
      var isShowMask = false;
      that.goBuy();
    } else {
      app.showToast("请勾选下单须知");
    }
  },
  //查询评论列表
  getEvaluateList() {
    var that = this;
    var equipments_id = that.data.equipments_id;
    app.ajax({
      url: 'User/Order/getEvaluateList',
      method: "POST",
      data: {
        equipments_id: equipments_id,
        page: _PAGE,
        pageSize: _PAGESIZE
      },
      success: function(res) {
        if (res.data.code == 1000) {
          if (_PAGE == 1) {
            that.setData({
              reviews: res.data.data,
              empty: false
            });
          } else {
            that.setData({
              reviews: that.data.reviews.concat(res.data.data),
              empty: false
            });
          }
          // 是否加载更多
          var hasMore = true;
          if (res.data.data.length < _PAGESIZE) {
            hasMore = false;
          }
          that.setData({
            hasMore: hasMore,
            loading: false
          });
        } else {
          if (_PAGE == 1) {
            that.setData({
              hasMore: false,
              loading: false,
              empty: true
            })
          } else {
            that.setData({
              hasMore: false,
              loading: false,
              empty: false
            })
          }
        }
        that.setData({
          loadShow: true
        })
      }
    })
  },
  //放大图片
  bigIng: function(e) {
    //var imgs = [];
    //imgs.push(e.currentTarget.dataset.src);
    // wx.previewImage({
    //   urls: imgs,
    // })
    wx.previewImage({
      current: e.currentTarget.dataset.src,
      urls: e.currentTarget.dataset.list,
    })
  },
  //图片加载错误
  binderrorimg(e) {
    var index = e.target.dataset.errorindex,
      that = this,
      equipments = that.data.equipments;
    equipments.shuffling_pic[index] = '../../../images/none.png';
    that.setData({
      equipments: equipments
    })
  },
  binderrormain_pic(e) {
    var that = this,
      equipments = that.data.equipments;
    equipments.main_pic = '../../../images/none.png';
    that.setData({
      equipments: equipments
    })
  },

  // 获取用户信息
  getUserInfo() {
    var that = this;
    app.ajax({
      url: 'User/User/getUserInfo',
      method: "POST",
      data: {},
      success: function(res) {
        if (res.data.code == 1000) {
          is_rent_eq = res.data.data.is_rent_eq;
          userInfo = res.data.data
        }
      }
    })
  },

  // 客服
  customerService(){
    wx.navigateTo({
      url: '../../customService/customService',
    })
  },
  //分享记录
  shareLogFun(s_way) {
    var that = this;
    app.ajax({
      url: 'User/Share/shareLog',
      method: "POST",
      data: { type: 2, share_way: s_way },//1是邀请好友 2分享详情
      success: function (res) {
        if (res.data.code = 1000) {

        } else {

        }
      }

    })
  },
  //浏览记录
  shareLogHistory() {
    var that = this;
    app.ajax({
      url: 'User/Browse/browseLog',
      method: "POST",
      data: { browse_page: 'pages/shopping/goodsDetail/goodsDetail' },//1是邀请好友 2分享详情
      success: function (res) {
        if (res.data.code = 1000) {

        } else {

        }
      }

    })
  },

})
